import requests
import json
from util.logger import get_logger

logger = get_logger('yuanshen.log', __file__)
iChanId = [727, 728, 729, 730, 731, 936, 1219]

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36'
}

for num in iChanId:
    logger.info(f"开始爬取iChanId为{num}的国家角色")

    url = f'https://act-api-takumi-static.mihoyo.com/content_v2_user/app/16471662a82d418a/getContentList?iAppId=43&iChanId={num}&iPageSize=50&iPage=1&sLangKey=zh-cn&iOrder=6'

    response = requests.get(url, headers=headers)
    datas = response.json()['data']['list']

    for data in datas:
        title = data['sTitle']
        img_url = data['sExt']
        img_url_json = json.loads(img_url)


        for item in img_url_json['732_15']:
            phone_img = item['url']
            logger.info(f"{title}, {phone_img}")

            if phone_img:
                img = requests.get(phone_img, headers=headers)
                try:
                    with open(f'static/yuanshen/{title}.png', 'wb') as f:
                        f.write(img.content)
                        logger.info("图片保存成功")
                except Exception as e:
                    logger.error(e)

            else:
                logger.error("图片地址不存在")

    logger.info("爬取结束")

